<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElDialog } from 'element-plus'
import { useRoute } from "vue-router";
import axios from "axios";

const route = useRoute()
const status = ref(Number(route.query.status))

// 表单数据
const formData = ref({

  templateName: 'xx运费模板',
  province: '',
  city: '',
  area: '',
  bear: 1,
  expressCompany: '',
  isFreight: 0, // 新增：是否设置包邮条件
  billingRules:status.value,
  freight: [
    {    // 新增：包邮条件数据
    address: [],
    shippingId: '',
    condition: ''
  }
  ],
  destinations: [
    {
      status:status.value,
      destination: [],
      low: '',
      mid: '',
      high: '',
      addWeight: '',
      volume: '',
      addVolume: '',
      amount: '',
      addAmount: ''
    }
  ]
})

// 编辑状态
const editingIndex = ref(null)
const editingFreightIndex = ref(null) // 新增：包邮条件编辑索引
const showProvinceDialog = ref(false)
const currentEditingIndex = ref(0)
const selectedProvinces = ref([])

// 地址选项
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const expressCompanyOptions = ref([])

const getAllExpressCompanies = () => {
  axios.get(`/shippingCompany/getAllExpressCompanies`).then(resp => {
    expressCompanyOptions.value = resp.data.map(item => ({
      value: item.id,
      label: item.name
    }))

  })

}

// 获取省份数据
const getAllProvinces = async () => {
  try {
    const resp = await axios.get("/china/provinces")
    provinceOptions.value = resp.data.map(item => ({
      value: item.id || item.code,
      label: item.name
    }))
  } catch (error) {
    ElMessage.error('获取省份数据失败')
    console.error(error)
  }
}
const openProvinceDialog = (index) => {
  currentEditingIndex.value = index
  selectedProvinces.value = [...formData.value.destinations[index].destination]
  showProvinceDialog.value = true
}

// 保存选择的省份
const saveSelectedProvinces = () => {
  formData.value.destinations[currentEditingIndex.value].destination = [...selectedProvinces.value]
  showProvinceDialog.value = false
  ElMessage.success('目的地已更新')
}

// 取消选择
const cancelProvinceSelection = () => {
  showProvinceDialog.value = false
}

// 获取城市数据
const getCitiesByProvince = async (provinceCode) => {
  try {
    const resp = await axios.get(`/china/cities/${provinceCode}`)
    cityOptions.value = resp.data.map(item => ({
      value: item.id || item.code,
      label: item.name
    }))
    formData.value.city = ''
    districtOptions.value = []
  } catch (error) {
    ElMessage.error('获取城市数据失败')
    console.error(error)
  }
}

// 获取区县数据
const getAreasByCity = async (cityCode) => {
  try {
    const resp = await axios.get(`/china/areas/${cityCode}`)
    districtOptions.value = resp.data.map(item => ({
      value: item.id || item.code,
      label: item.name
    }))
    formData.value.area = ''
  } catch (error) {
    ElMessage.error('获取区县数据失败')
    console.error(error)
  }
}

// 地址选择变化处理
const handleProvinceChange = (provinceCode) => {
  if (provinceCode) {
    getCitiesByProvince(provinceCode)
  }
}

const handleCityChange = (cityCode) => {
  if (cityCode) {
    getAreasByCity(cityCode)
  }
}

// 添加新省份
const handleAddProvince = () => {
  formData.value.destinations.push({
    status:status.value,
    destination: '',
    low: '',
    mid: '',
    high: '',
    addWeight: '',
    volume: '',
    addVolume: '',
    amount: '',
    addAmount: ''
  })
  editingIndex.value = formData.value.destinations.length - 1
}

// 编辑操作


const showFreightProvinceDialog = ref(false)
const currentEditingFreightIndex = ref(0)
const selectedFreightProvinces = ref([])

// 添加这些新方法用于包邮条件省份选择
const openFreightProvinceDialog = (index) => {
  currentEditingFreightIndex.value = index
  selectedFreightProvinces.value = [...formData.value.freight[index].address]
  showFreightProvinceDialog.value = true
}

const saveSelectedFreightProvinces = () => {
  formData.value.freight[currentEditingFreightIndex.value].address = [...selectedFreightProvinces.value]
  showFreightProvinceDialog.value = false
  ElMessage.success('包邮区域已更新')
}

const cancelFreightProvinceSelection = () => {
  showFreightProvinceDialog.value = false
}

// 保存编辑
const handleSave = (index) => {
  editingIndex.value = null
  ElMessage.success('保存成功')
}

// 删除操作
const handleDelete = (index) => {
  formData.value.destinations.splice(index, 1)
  ElMessage.success('删除成功')
  if (editingIndex.value === index) {
    editingIndex.value = null
  }
}

// 新增：添加包邮条件
const handleAddFreight = () => {
  formData.value.freight.push({
    address: [],
    shippingId: '',
    condition: ''
  })
  editingFreightIndex.value = formData.value.freight.length - 1
}

// 新增：编辑包邮条件
const handleEditFreight = (index) => {
  editingFreightIndex.value = index
}
// 新增：删除包邮条件
const handleDeleteFreight = (index) => {
  formData.value.freight.splice(index, 1)
  ElMessage.success('包邮条件删除成功')
  if (editingFreightIndex.value === index) {
    editingFreightIndex.value = null
  }
}

// 新增：获取包邮条件前缀文本
const getConditionPrefix = computed(() => {
  switch (status.value) {
    case 1: return '满'
    case 2: return '满'
    case 3: return '满'
    default: return '满'
  }
})

// 新增：获取包邮条件后缀文本
const getConditionSuffix = computed(() => {
  switch (status.value) {
    case 1: return 'kg包邮'
    case 2: return 'm³包邮'
    case 3: return '件包邮'
    default: return ''
  }
})

const  saveTemplate =()=>{
  axios.post('/shippingTemplate/addShippingTemplate', formData.value).then((resp) => {
    ElMessage.success(resp.data);
  })
}

// 初始化获取省份数据
onMounted(() => {
  getAllExpressCompanies()

  getAllProvinces()
})
</script>

<template>
  <div class="shipping-template-container">
    <el-card class="template-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2 class="header-title">添加运费模板</h2>
        </div>
      </template>

      <!-- 模板名称 -->
      <div class="form-section">
        <h3 class="section-title">模板名称：</h3>
        <el-input
            v-model="formData.templateName"
            placeholder="请输入模板名称"
            class="form-input"
        />
      </div>

      <!-- 商品地址 -->
      <div class="form-section">
        <h3 class="section-title">商品地址：</h3>
        <div class="address-selectors">
          <el-select
              v-model="formData.province"
              placeholder="请选择省"
              @change="handleProvinceChange"
              class="address-selector"
          >
            <el-option
                v-for="province in provinceOptions"
                :key="province.value"
                :label="province.label"
                :value="province.value"
            />
          </el-select>

          <el-select
              v-model="formData.city"
              placeholder="请选择市"
              @change="handleCityChange"
              :disabled="!formData.province"
              class="address-selector"
          >
            <el-option
                v-for="city in cityOptions"
                :key="city.value"
                :label="city.label"
                :value="city.value"
            />
          </el-select>

          <el-select
              v-model="formData.area"
              placeholder="请选择区/县"
              :disabled="!formData.city"
              class="address-selector"
          >
            <el-option
                v-for="area in districtOptions"
                :key="area.value"
                :label="area.label"
                :value="area.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 运费承担 -->
      <div class="form-section">
        <h3 class="section-title">运费承担：</h3>
        <el-radio-group v-model="formData.shippingBearer" class="radio-group">
          <el-radio :label="1" size="large">买家承担运费</el-radio>
          <el-radio :label="2" size="large">卖家承担运费</el-radio>
        </el-radio-group>
      </div>

      <!-- 快递公司 -->
      <div class="form-section">
        <h3 class="section-title">快递公司：</h3>
        <el-select
            v-model="formData.expressCompany"
            placeholder="请选择快递公司"
            class="form-input"
        >
          <el-option
              v-for="item in expressCompanyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>

      <!-- 运送到 -->
      <div class="form-section">
        <h3 class="section-title">运送到：</h3>
        <el-table
            :data="formData.destinations"
            style="width: 100%"
            border
            stripe
            class="shipping-table"
        >
          <el-table-column
              prop="destination"
              label="目的地"
              width="200"
              align="center"
          >
            <template #default="scope">
              <div class="destination-display">
              <span v-if="scope.row.destination.length > 0">
                {{ scope.row.destination.join(', ') }}
              </span>
                <span v-else>未设置</span>
                <el-button
                    size="small"
                    type="primary"
                    @click="openProvinceDialog(scope.$index)"
                    class="edit-btn"
                >编辑</el-button>
              </div>
            </template>
          </el-table-column>

          <!-- status=1 按重量 -->
          <template v-if="status === 1">
            <el-table-column
                label="商品≤1kg"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.low" :min="0" :controls="false" />
              </template>
            </el-table-column>
            <el-table-column
                label="1kg<商品≤2kg"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.mid" :min="0" :controls="false" />
              </template>
            </el-table-column>
            <el-table-column
                label="2kg<商品≤3kg"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.high" :min="0" :controls="false" />
              </template>
            </el-table-column>
            <el-table-column
                label="每增加1kg的额外费用"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.addWeight" :min="0" :controls="false" />
              </template>
            </el-table-column>
          </template>

          <!-- status=2 按体积 -->
          <template v-else-if="status === 2">
            <el-table-column
                label="商品≤10m³"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.volume" :min="0" :controls="false" />
              </template>
            </el-table-column>
            <el-table-column
                label="每增加1m³的额外费用"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.addVolume" :min="0" :controls="false" />
              </template>
            </el-table-column>
          </template>

          <!-- status=3 按件数 -->
          <template v-else-if="status === 3">
            <el-table-column
                label="件数≤10"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.amount" :min="0" :controls="false" />
              </template>
            </el-table-column>
            <el-table-column
                label="每增加1件的额外费用"
                align="center"
            >
              <template #default="scope">
                <el-input-number v-model="scope.row.addAmount" :min="0" :controls="false" />
              </template>
            </el-table-column>
          </template>

          <el-table-column
              label="操作"
              width="120"
              align="center"
          >
            <template #default="scope">
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index)"
                  class="action-btn"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="add-province-btn">
          <el-button
              type="primary"
              @click="handleAddProvince"
              icon="Plus"
          >添加省份，设置运费</el-button>
        </div>
      </div>

      <!-- 新增：包邮条件设置 -->
      <div class="form-section">
        <div class="freight-header">
          <el-checkbox v-model="formData.isFreight" :true-label="1" :false-label="0">
            设置包邮条件
          </el-checkbox>
        </div>

        <el-table
            v-if="formData.isFreight === 1"
            :data="formData.freight"
            style="width: 100%"
            border
            stripe
            class="freight-table"
        >
          <el-table-column
              label="选择地区"
              width="200"
              align="center"
          >
            <template #default="scope">
              <div class="destination-display">
        <span v-if="scope.row.address.length > 0">
          {{ scope.row.address.join(', ') }}
        </span>
                <span v-else>未设置</span>
                <el-button
                    size="small"
                    type="primary"
                    @click="openFreightProvinceDialog(scope.$index)"
                    class="edit-btn"
                >编辑</el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="选择运送方式"
              align="center"
          >
            <template #default="scope">
              <el-select
                  v-model="scope.row.shippingId"
                  placeholder="请选择快递公司"
                  class="form-input"
              >
                <el-option
                    v-for="item in expressCompanyOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column
              label="设置包邮条件"
              align="center"
          >
            <template #default="scope">
              <div class="condition-input">
                <span>{{ getConditionPrefix }}</span>
                <el-input
                    v-model="scope.row.condition"
                    :placeholder="`请输入${getConditionSuffix.replace('包邮','')}`"
                    :min="0"
                    style="width: 80px; margin: 0 5px"
                />
                <span>{{ getConditionSuffix }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="操作"
              width="180"
              align="center"
          >
            <template #default="scope">
              <template v-if="editingFreightIndex === scope.$index">
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDeleteFreight(scope.$index)"
                    class="action-btn"
                >删除</el-button>
              </template>
              <template v-else>
                <el-button
                    size="small"
                    type="primary"
                    @click="handleEditFreight(scope.$index)"
                    class="action-btn"
                >编辑</el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDeleteFreight(scope.$index)"
                    class="action-btn"
                >删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog
            v-model="showFreightProvinceDialog"
            title="选择包邮区域"
            width="50%"
        >
          <div class="province-dialog-content">
            <el-checkbox-group v-model="selectedFreightProvinces">
              <div class="province-checkbox" v-for="province in provinceOptions" :key="province.value">
                <el-checkbox :label="province.label">{{ province.label }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <template #footer>
          <span class="dialog-footer">
        <el-button @click="cancelFreightProvinceSelection">取消</el-button>
        <el-button type="primary" @click="saveSelectedFreightProvinces">
          保存
        </el-button>
      </span>
          </template>
        </el-dialog>

        <div v-if="formData.isFreight === 1" class="freight-footer">
          <el-button
              type="primary"
              @click="handleAddFreight"
              icon="Plus"
          >添加包邮条件</el-button>
        </div>
        <el-dialog
            v-model="showProvinceDialog"
            title="选择区域"
            width="50%"
        >
          <div class="province-dialog-content">
            <el-checkbox-group v-model="selectedProvinces">
              <div class="province-checkbox" v-for="province in provinceOptions" :key="province.value">
                <el-checkbox :label="province.label">{{ province.label }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelProvinceSelection">取消</el-button>
          <el-button type="primary" @click="saveSelectedProvinces">
            保存
          </el-button>
        </span>
          </template>
        </el-dialog>
      </div>

      <!-- 底部按钮 -->
      <div class="form-actions">
        <el-button
            type="primary"
            size="large"
            @click="saveTemplate"
        >保存</el-button>
        <el-button
            type="info"
            size="large"
            @click="$router.back()"
        >取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.shipping-template-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.template-card {
  margin-top: 16px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.form-section {
  margin-bottom: 28px;
  padding: 0 16px;
}

.section-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-input {
  width: 100%;
  max-width: 400px;
}

.radio-group {
  margin-top: 8px;
}

.shipping-table, .freight-table {
  margin-top: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.action-btn {
  margin: 0 4px;
}

.address-selectors {
  display: flex;
  gap: 12px;
}

.address-selector {
  flex: 1;
  min-width: 120px;
}

.add-province-btn, .freight-footer {
  margin-top: 16px;
  text-align: left;
}

.destination-display, .freight-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.destination-edit, .freight-edit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.edit-input {
  flex: 1;
}

.edit-btn, .save-btn {
  margin-left: 8px;
}

.condition-input {
  display: flex;
  align-items: center;
  justify-content: center;
}

.freight-header {
  margin-bottom: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding: 20px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .address-selectors {
    flex-direction: column;
    gap: 8px;
  }

  .address-selector {
    width: 100%;
  }

  .destination-display, .destination-edit,
  .freight-display, .freight-edit {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .edit-btn, .save-btn {
    margin-left: 0;
    width: 100%;
  }

  .condition-input {
    flex-direction: column;
    gap: 5px;
  }
}

.el-input-number {
  width: 100px;
}

.province-dialog-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.province-checkbox {
  margin: 8px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>